#!/usr/bin/python2.5
# -*- coding: cp1250 -*-
#
# Copyright 2008 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
kindly.cz application

main page and download page handlers
"""

__author__ = 'Nikola Tepper'

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import taskqueue
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

import string
import settings
import timezones 

from models import *
from basehandler import *
from datetime import *

class Index(BaseHandler):
    """
    Handler for main page
    
    simply list active periodicals and offer download links
    """        
    def get(self):
        # if we're in dev environ, generate test data and run check task immediately
        environment = os.environ["SERVER_SOFTWARE"]
        if "Development" in environment:            
            #taskqueue.add(url='/cron/checkupdates', method='GET')
            pass
                        
        periodicals = Periodical.allActiveView()
        self.render_to_response('index.html', {'periodicals': periodicals})
        
class Rss(BaseHandler):
    """
    Handler for RSS feed
    
    Returns a feed with latest file updates
    """    
    def get(self):        
        periodicals = Periodical.allActiveView()        
        self.response.headers['Content-Type'] = 'application/rss+xml'        
        self.render_to_response('rss.xml', 
                                {'periodicals': periodicals})  
    
class Help(BaseHandler):
    """
    Handler for help page
    
    Shows some basic help and FAQ
    """    
    def get(self):     
        self.render_to_response('help.html', 
                                {'dummy': None}) 
        
class Books(BaseHandler):
    """
    Handler for books page
    
    Shows some basic help and FAQ
    """    
    def get(self):     
        self.render_to_response('books.html', 
                                {'dummy': None}) 
        
class Stats(BaseHandler):
    """
    Handler for Stats page
    
    Shows statistics
    """    
    def get(self):
        
        stats =  PeriodicalStats.getStats(datetime.now().date())            
        bookStats =  BookDownloadStats.getStats()            
        
        statInfo = {}
        statInfo["updated"] = max(stats, key=lambda stat: stat["updated"])["updated"] #pick latest time 
        statInfo["max"] = max(stats, key=lambda stat: stat["subscribers"])["subscribers"]
        statInfo["maxBooks"] = max(bookStats, key=lambda stat: stat["downloaded"])["downloaded"]
            
        self.render_to_response('stats.html', 
                                {'statInfo': statInfo,
                                 'stats': stats,
                                 'bookStats' : bookStats}) 
        
class Download(blobstore_handlers.BlobstoreDownloadHandler):    
    def get(self, encoded_name):        

        # use key to retrieve periodical
        periodical_name = encoded_name.lower().replace("%20", " ")
        periodical = Periodical.get_by_key_name(periodical_name)
        
        if periodical and periodical.blobfile:                 
            logging.debug("Download request for %s" % periodical_name)
            download_stat = PeriodicalDownloadStats(parent = periodical,
                                                    user=users.get_current_user())
            download_stat.put() 
            
            # get from blobstore
            blob_info = periodical.blobfile
            self.send_blob(blob_info, save_as=True)
            
            #finalUrl = settings.SERVICE_URL + "GetFile.aspx?file=" + encoded_name
            #logging.debug("Redirecting to %s" % finalUrl)
            #self.redirect(finalUrl) # just show index if not found          
        else: 
            logging.debug("Download request for non-existing file %s" % periodical_name)   
            self.redirect('/') # just show index if not found
            
class DownloadBook(BaseHandler):
    """
    Handler for Download Book page
    """    
    def get(self, encoded_name):   
        
        book_name = encoded_name.lower().replace("%20", " ")
        book = Book.get_by_key_name(book_name)
        
        if book:                 
            logging.debug("Download book request for %s" % book_name)
            download_stat = BookDownloadStats(parent = book,
                                              user=users.get_current_user())  
            download_stat.put()            
         
            finalUrl = settings.STORAGE_URL + encoded_name
            logging.debug("Redirecting to %s" % finalUrl)
            self.redirect(finalUrl)
        else:
            logging.debug("Download request for non-existing book file %s" % book_name)   
            self.redirect('/') # just show index if not found

    
def main():
    url_map = [('/', Index),
               ('/rss', Rss),
               ('/help', Help),
               ('/stats', Stats),
               ('/books', Books),
               ('/download/(.*)', Download),
               ('/downloadBook/(.*)', DownloadBook)]
    
    application = webapp.WSGIApplication(url_map, debug=True)
    run_wsgi_app(application)
    #wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()